/*
 * Copyright 2020 DuJiang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.amorou.rest.crypto.advice;

import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.amorou.rest.crypto.annotation.ResponseBodyEncrypt;
import cn.amorou.rest.crypto.boot.RestCryptoProperties;
import cn.amorou.rest.crypto.util.CryptoUtils;

/**
 * EncryptResponseBodyAdvice
 * 
 * @author DuJiang
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private RestCryptoProperties cryptoProperties;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return returnType.getMethod().isAnnotationPresent(ResponseBodyEncrypt.class);
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		try {
			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(body));
			Set<Entry<String, Object>> entrySet = jsonObject.entrySet();
			for (Entry<String, Object> entry : entrySet) {
				jsonObject.put(entry.getKey(), CryptoUtils.aesEncrypt(entry.getValue().toString(), cryptoProperties.getAesKey(), cryptoProperties.getAesIv(), cryptoProperties.getCharset()));
			}
			return jsonObject;
		} catch (Exception e) {
			log.error("ResponseBody encrypted data exception", e);
		}
		return body;
	}

}